package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.YzStudentBirthday;
import com.ruoyi.system.service.IYzStudentBirthdayService;
import com.ruoyi.system.util.Lunar;
import com.ruoyi.system.util.LunarSolarConverter;
import com.ruoyi.system.util.Solar;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * 员工信息Controller
 *
 * @author linpq
 * @date 2020-04-10
 */
@Controller
@RequestMapping("/system/birthday")
public class YzStudentBirthdayController extends BaseController
{
    private String prefix = "system/birthday";

    @Autowired
    private IYzStudentBirthdayService yzStudentBirthdayService;

    @RequiresPermissions("system:birthday:view")
    @GetMapping()
    public String birthday(ModelMap mmap)
    {

        Calendar c = Calendar.getInstance();
//        int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
//        if (day_of_week == 0)
//            day_of_week = 7;
//        c.add(Calendar.DATE, -day_of_week + 1);
//        mmap.put("beginshengRi", DateUtils.parseDateToStr("YYYY-MM-dd",c.getTime()));
//        mmap.put("beginshengRi", DateUtils.parseDateToStr("YYYY-MM-dd",c.getTime()));
//        c.add(Calendar.DATE, 7);
//        mmap.put("endshengRi", DateUtils.parseDateToStr("YYYY-MM-dd",c.getTime()));


        c .set(Calendar.DAY_OF_MONTH,1);
        mmap.put("beginshengRi", DateUtils.parseDateToStr("YYYY-MM-dd",c.getTime()));
        c .add(Calendar.MONTH,1);
        c .set(Calendar.DAY_OF_MONTH,0);
        mmap.put("endshengRi", DateUtils.parseDateToStr("YYYY-MM-dd",c.getTime()));

        return prefix + "/birthday";
    }

    /**
     * 查询员工信息列表
     */
    @RequiresPermissions("system:birthday:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YzStudentBirthday yzStudentBirthday)
    {
        startPage();
        List<YzStudentBirthday> list = yzStudentBirthdayService.selectYzStudentBirthdayList(yzStudentBirthday);
        return getDataTable(list);
    }

    /**
     * 导出员工信息列表
     */
    @RequiresPermissions("system:birthday:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YzStudentBirthday yzStudentBirthday)
    {
        List<YzStudentBirthday> list = yzStudentBirthdayService.selectYzStudentBirthdayList(yzStudentBirthday);
        ExcelUtil<YzStudentBirthday> util = new ExcelUtil<YzStudentBirthday>(YzStudentBirthday.class);
        return util.exportExcel(list, "birthday");
    }
    /**
     * 跨年手动更新
     */
    @PostMapping("/updateNewYear")
    @ResponseBody
    public AjaxResult updateNewYear(YzStudentBirthday yzStudentBirthday1)
    {
        List<YzStudentBirthday> list = yzStudentBirthdayService.selectYzStudentBirthdayList(yzStudentBirthday1);

        for(YzStudentBirthday yzStudentBirthday : list){




            String []arr = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
            Calendar calendar = Calendar.getInstance();

            String month = yzStudentBirthday.getShengRi().substring(4,6);
            String day = yzStudentBirthday.getShengRi().substring(6,8);

            int year = Calendar.getInstance().get(Calendar.YEAR);
            if(yzStudentBirthday.getYuLiu1().startsWith((year-1)+"")){
                yzStudentBirthday.setYuLiu3("0");
            }

            //农历
            if(yzStudentBirthday.getNongHuoXin().equals("农历")){
                Lunar l = new Lunar();
                l.isleap = false;
                l.lunarDay = Integer.parseInt(day);
                l.lunarMonth = Integer.parseInt(month);
                l.lunarYear = year;
                Solar solar = LunarSolarConverter.LunarToSolar(l);


                if(solar.solarYear>year){
                    l.lunarYear = year-1;
                }
                solar = LunarSolarConverter.LunarToSolar(l);

                yzStudentBirthday.setYuLiu1(""+solar.solarYear+"-"+(solar.solarMonth<10?"0"+solar.solarMonth:solar.solarMonth)+"-"+(solar.solarDay<10?"0"+solar.solarDay:solar.solarDay));

                calendar.set(solar.solarYear,solar.solarMonth-1,solar.solarDay);

                yzStudentBirthday.setYuLiu2(arr[calendar.get(Calendar.DAY_OF_WEEK)-1]);
            }else {

                yzStudentBirthday.setYuLiu1(""+year+"-"+month+"-"+day);

                calendar.set(year,Integer.parseInt(month)-1,Integer.parseInt(day));
                yzStudentBirthday.setYuLiu2(arr[calendar.get(Calendar.DAY_OF_WEEK)-1]);
            }


            yzStudentBirthdayService.updateYzStudentBirthday(yzStudentBirthday);
        }

        ExcelUtil<YzStudentBirthday> util = new ExcelUtil<YzStudentBirthday>(YzStudentBirthday.class);
        return toAjax(1);
    }

    /**
     * 新增员工信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存员工信息
     */
    @RequiresPermissions("system:birthday:add")
    @Log(title = "员工信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YzStudentBirthday yzStudentBirthday)
    {

        yzStudentBirthday =  preSave(yzStudentBirthday);

        return toAjax(yzStudentBirthdayService.insertYzStudentBirthday(yzStudentBirthday));
    }

    private YzStudentBirthday preSave(YzStudentBirthday yzStudentBirthday){
        String []arr = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar calendar = Calendar.getInstance();
        System.out.println("今天是："+arr[calendar.get(Calendar.DAY_OF_WEEK)-1]);

        String month = yzStudentBirthday.getShengRi().substring(4,6);
        String day = yzStudentBirthday.getShengRi().substring(6,8);

        int year = Calendar.getInstance().get(Calendar.YEAR);
        //农历
        if(yzStudentBirthday.getNongHuoXin().equals("农历")){
            Lunar l = new Lunar();
            l.isleap = false;
            l.lunarDay = Integer.parseInt(day);
            l.lunarMonth = Integer.parseInt(month);
            l.lunarYear = year;
            Solar solar = LunarSolarConverter.LunarToSolar(l);
            yzStudentBirthday.setYuLiu1(""+solar.solarYear+"-"+(solar.solarMonth<10?"0"+solar.solarMonth:solar.solarMonth)+"-"+(solar.solarDay<10?"0"+solar.solarDay:solar.solarDay));

            calendar.set(solar.solarYear,solar.solarMonth-1,solar.solarDay);

            yzStudentBirthday.setYuLiu2(arr[calendar.get(Calendar.DAY_OF_WEEK)-1]);
        }else {

            yzStudentBirthday.setYuLiu1(""+year+"-"+month+"-"+day);

            calendar.set(year,Integer.parseInt(month)-1,Integer.parseInt(day));
            yzStudentBirthday.setYuLiu2(arr[calendar.get(Calendar.DAY_OF_WEEK)-1]);
        }

        return yzStudentBirthday;
    }

    /**
     * 修改员工信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        YzStudentBirthday yzStudentBirthday = yzStudentBirthdayService.selectYzStudentBirthdayById(id);
        mmap.put("yzStudentBirthday", yzStudentBirthday);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工信息
     */
    @RequiresPermissions("system:birthday:edit")
    @Log(title = "员工信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YzStudentBirthday yzStudentBirthday)
    {
        return toAjax(yzStudentBirthdayService.updateYzStudentBirthday(preSave(yzStudentBirthday)));
    }

    /**
     * 删除员工信息
     */
    @RequiresPermissions("system:birthday:remove")
    @Log(title = "员工信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(yzStudentBirthdayService.deleteYzStudentBirthdayByIds(ids));
    }


    /**
     * 用户状态修改
     */
    @Log(title = "礼物送达", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(YzStudentBirthday yzStudentBirthday)
    {
        return toAjax(yzStudentBirthdayService.changeStatus(yzStudentBirthday));
    }


    /**
     * 下载模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<YzStudentBirthday> util = new ExcelUtil<YzStudentBirthday>(YzStudentBirthday.class);
        return util.importTemplateExcel("员工数据");
    }


    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<YzStudentBirthday> util = new ExcelUtil<YzStudentBirthday>(YzStudentBirthday.class);
        List<YzStudentBirthday> userList = util.importExcel(file.getInputStream());
        String message = importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    public String importUser(List<YzStudentBirthday> userList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入员工数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (YzStudentBirthday user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                boolean userFlag = false;
                List<YzStudentBirthday> users = yzStudentBirthdayService.selectYzStudentBirthdayList(new YzStudentBirthday());
                for (YzStudentBirthday entry : users)
                {
                    if (entry.getShouJiHaoMa().equals(user.getShouJiHaoMa()))
                    {
                        userFlag = true;
                        break;
                    }
                }
                if (!userFlag)
                {
                    Integer userId = users.size() + 1;
                    yzStudentBirthdayService.insertYzStudentBirthday(preSave(user));
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + user.getXingMing()+"/"+ user.getShouJiHaoMa() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    successNum++;
                    yzStudentBirthdayService.updateYzStudentBirthday(preSave(user));
                    successMsg.append("<br/>" + successNum + "、员工 " + user.getXingMing()+"/"+ user.getShouJiHaoMa() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工 " + user.getXingMing()+"/"+ user.getShouJiHaoMa() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getXingMing()+"/"+ user.getShouJiHaoMa() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
